// 运行时配置

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://next.umijs.org/docs/api/runtime-config#getinitialstate
// export async function getInitialState(): Promise<{ name: string }> {
//   return { name: '@umijs/max' };
// }

import type { RequestConfig } from '@umijs/max'
import { history } from '@umijs/max'
import { notification } from '@/utils/AntdGlobal'
import { clearLogin, checkTarget } from '@/utils/utils'
import './app.less'
import '../public/iconfont.css'

if (!(window as any).messagePipline) (window as any).messagePipline = {}
// 子项目通信
window.addEventListener('message', e => {
  if (e.data?.frameMessage) {
    const { data, action } = e.data
    switch (action) {
      case 'open':
        const url = data.url.startsWith('#') ? data.url.replace('#', '') : data.url
        window.open(url)
        break
      case 'route':
        const path = data.path
        history.push(path)
        break

      default:
        console.log('message err, on match action:', action)
        return
    }
  } else if (e.data.frameResponse) {
    const key = e.data.reciveKey

    const id = (window as any).messagePipline[key]
    ;(window as any).messagePipline[key] = null
    clearTimeout(id)
  }
})

export const request: RequestConfig = {
  timeout: 60000,
  baseURL: process.env.BASE_URL,
  // credentials: 'include',
  // headers: {
  //   "jwt-token": localStorage.getItem('jwt-token') || sessionStorage.getItem('jwt-token') || '',
  // },

  // other axios options you want
  errorConfig: {
    errorHandler(err) {
      const errMsg = err.response?.data?.msg
      notification?.error({
        message: errMsg ? '' : `网络错误`,
        description: errMsg || err.message
      })
    },
    errorThrower(err) {
      console.log('errorThrower', err)
    }
  },
  requestInterceptors: [],
  responseInterceptors: [
    (response: any) => {
      // 不再需要异步处理读取返回体内容，可直接在data中读出，部分字段可在 config 中找到
      // const { data: { code, data, msg } = {} as any, config } = response;
      const {
        data: { code, data, msg } = {} as any,
        config: { hideNotice = false }
      } = response
      // if (response.data instanceof Blob) {
      //   return response;
      // } else if (code === 200) {
      if (code === 200) {
        return {
          ...response,
          data
        }
        // } else if (code === 401) {
        //   clearLogin();
        //   const path = window.location.pathname;
        //   const target = path ? `/login?target=${path}` : '/login';
        //   history.push(target);
      } else {
        if (!hideNotice) {
          notification?.warning({
            message: `请求错误`,
            description: msg
          })
        }
        if (code === 109) {
          clearLogin()
          const path = window.location.pathname
          const target = path ? `/main/login?target=${checkTarget(path)}` : '/main/login'
          history.push(target)
        }
        return false
      }
    }
  ]
}

window._AMapSecurityConfig = {
  securityJsCode: '6ac887a131059d50b55cf819da7201c9'
}

const url =
  'https://webapi.amap.com/maps?v=1.4.15&key=8c49acc18d5a930663be50397d09a4da&plugin=AMap.Autocomplete,AMap.PlaceSearch'
const jsapi = document.createElement('script')
jsapi.src = url
document.head.appendChild(jsapi)
